//
//  SweepViewController.m
//  110
//
//  Created by 沈鑫 on 16/4/18.
//  Copyright © 2016年 乔砥. All rights reserved.
//

#import "SweepViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "WebViewController.h"
@interface SweepViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIWebViewDelegate>
@property (nonatomic, strong)UILabel *lblStatus;
@property (nonatomic, strong)UIButton *startButton;
@property (nonatomic, strong)UIView *viewPreview;

@property (strong, nonatomic) UIView *boxView;
@property (nonatomic) BOOL isReading;
@property (strong, nonatomic) CALayer *scanLayer;

-(BOOL)startReading;
-(void)stopReading;


//捕捉会话
@property (nonatomic, strong) AVCaptureSession *captureSession;
//展示layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
// 闪光灯
@property (nonatomic, strong) UIButton *lightButton;
@property (nonatomic, assign) BOOL isok;

@property (nonatomic, strong) UIWebView *myWebView;

@end

@implementation SweepViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    
    // navigation两边button 的颜色
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    // navigation字体的颜色 大写 型号
    [self.navigationController.navigationBar setTitleTextAttributes: @{NSFontAttributeName: [UIFont fontWithName:@"Arial-BoldItalicMT" size:19],
                                                                       
                                                                       
                                                                       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    _captureSession = nil;
    _isReading = NO;
    
    _viewPreview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT / 2)];
    _viewPreview.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_viewPreview];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT / 2)];
    imageView.image = [UIImage imageNamed:@"saomiao"];
    [self.viewPreview addSubview:imageView];
    
    _lblStatus = [[UILabel alloc]initWithFrame:CGRectMake(100, 200, KWIDTH - 200, 30)];
    _lblStatus.hidden = YES;
    [self.viewPreview addSubview:_lblStatus];
    
    _startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_startButton setTitle:@"点我开始扫描" forState:UIControlStateNormal];
    [_startButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _startButton.frame = CGRectMake(100, 400, KWIDTH - 200, 30);
    [_startButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    // 点击发亮
    _startButton.showsTouchWhenHighlighted = YES;
    [_startButton addTarget:self action:@selector(startButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_startButton];
    
    _lightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _lightButton.frame = CGRectMake((KWIDTH - 30) / 2, 500, 30, 30);
    _lightButton.showsTouchWhenHighlighted = YES;
    [_lightButton addTarget:self action:@selector(lightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_lightButton setImage:[UIImage imageNamed:@"kaideng"] forState:UIControlStateNormal];
    [self.view addSubview:_lightButton];
}

#pragma mark --- 手电筒功能 ---
- (void)lightButtonAction:(UIButton *)button
{
     AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (!_isok)
    {
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            [device setTorchMode: AVCaptureTorchModeOn];
            [device unlockForConfiguration];
            [_lightButton setImage:[UIImage imageNamed:@"guandeng"] forState:UIControlStateNormal];
        }
    }
    else
    {
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            [device setTorchMode: AVCaptureTorchModeOff];
            [device unlockForConfiguration];
            [_lightButton setImage:[UIImage imageNamed:@"kaideng"] forState:UIControlStateNormal];
        }
    }
    _isok = !_isok;
}

- (BOOL)startReading {
    NSError *error;
    //1.初始化捕捉设备（AVCaptureDevice），类型为AVMediaTypeVideo
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //2.用captureDevice创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    //3.创建媒体数据输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    //4.实例化捕捉会话
    _captureSession = [[AVCaptureSession alloc] init];
    //4.1.将输入流添加到会话
    [_captureSession addInput:input];
    //4.2.将媒体输出流添加到会话中
    [_captureSession addOutput:captureMetadataOutput];
    //5.创建串行队列，并加媒体输出流添加到队列当中
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //5.1.设置代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    //5.2.设置输出媒体数据类型为QRCode
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeEAN13Code, nil]];
    //6.实例化预览图层
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    //7.设置预览图层填充方式
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    //8.设置图层的frame
    [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    //9.将图层添加到预览view的图层上
    [_viewPreview.layer addSublayer:_videoPreviewLayer];
    //10.设置扫描范围
    captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
    //10.1.扫描框
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.2f, _viewPreview.bounds.size.height * 0.2f, _viewPreview.bounds.size.width - _viewPreview.bounds.size.width * 0.4f, _viewPreview.bounds.size.height - _viewPreview.bounds.size.height * 0.4f) ];
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    [_viewPreview addSubview:_boxView];
    //10.2.扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
    _scanLayer.backgroundColor = [UIColor brownColor].CGColor;
    [_boxView.layer addSublayer:_scanLayer];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    [timer fire];
    
    //10.开始扫描
    [_captureSession startRunning];
    return YES;
}



#pragma mark - AVCaptureMetadataOutputObjectsDelegate -
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode] || [[metadataObj type] isEqualToString:AVMetadataObjectTypeEAN13Code] || [[metadataObj type] isEqualToString:AVMetadataObjectTypeEAN8Code] || [[metadataObj type] isEqualToString:AVMetadataObjectTypeCode128Code]) {
            [_lblStatus performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
            
            [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
           
            _isReading = NO;
    
            
        }
    }
}



- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = _scanLayer.frame;
    if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        frame.origin.y += 5;
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}

- (void)startButtonAction:(UIButton *)button
{
    if (!_isReading) {
        if ([self startReading]) {
            [_startButton setTitle:@"点我暂停扫描" forState:UIControlStateNormal];
        }
    }
    else{
        [self stopReading];
        [_startButton setTitle:@"点我开始扫描" forState:UIControlStateNormal];
    }
    _isReading = !_isReading;

}


- (void)stopReading{
    
    [_captureSession stopRunning];
    _captureSession = nil;
    [_scanLayer removeFromSuperlayer];
    [_videoPreviewLayer removeFromSuperlayer];
    
    if (_lblStatus.text.length == 0)
    {
        return;
    }
    WebViewController *web = [[WebViewController alloc]init];
    web.lblStatus = _lblStatus.text;
    NSLog(@"%@",web.lblStatus);
    [self.navigationController pushViewController:web animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
